﻿using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Extensions.DependencyInjection;
using RestfulApiV1.Data;
using RestfulApiV1.Data.Entity;
using RestfulApiV1.Implement.Data;
using RestfulApiV1.Interface.Data;
using System;
using System.Collections.Generic;
using System.Text;

namespace RestfulApiV1.Utils.DataBase
{
    public class DbInitializer
    {
        public static void Seed(IServiceProvider serviceProvider)
        {
            using(var scoped = serviceProvider.CreateScope())
            {
                var db = scoped.ServiceProvider.GetService(typeof(RestfulApiDbContext)) as RestfulApiDbContext;

                db.Database.EnsureCreated();

                var hasData = db.Users.Any();

                if (!hasData)
                {
                    var userRespository = scoped.ServiceProvider.GetService(typeof(IRespository<Users>)) as EfRespository<Users>;
                    var roleRespository = scoped.ServiceProvider.GetService(typeof(IRespository<Roles>)) as EfRespository<Roles>;
                    var userRoleRespository = scoped.ServiceProvider.GetService(typeof(IRespository<UserRole>)) as EfRespository<UserRole>;

                    var role = new Roles
                    {
                        RoleName = "管理员",
                        Description = "如你所料，这是一个管理员角色"
                    };

                    roleRespository.Add(role);

                    var adminUser = new Users
                    {
                        Username = "admin",
                        Password = "admin",
                    };

                    var user01User = new Users
                    {
                        Username = "user01",
                        Password = "123456",
                    };

                    userRespository.Add(adminUser);
                    userRespository.Add(user01User);

                    userRoleRespository.Add(new List<UserRole>
                    {
                        new UserRole
                        {
                            UsersId=adminUser.Id,
                            RolesId=role.Id
                        },
                        new UserRole
                        {
                            UsersId=user01User.Id,
                            RolesId=role.Id
                        }
                    });
                }

            }
        }
    }
}
